package observer;

import java.util.ArrayList;
import java.util.List;

// 观察者接口
interface Observer {
    void receive(String message);
}

// 具体的观察者
class UserEntity implements Observer {
    private final String name;

    public UserEntity(String name) {
        this.name = name;
    }

    @Override
    public void receive(String message) {
        System.out.println(name + " 收到通知: " + message);
    }
}

// 被观察者接口
interface Topic {
    void addObserver(Observer observer);
    void removeObserver(Observer observer);
    void notifyObservers(String message);
}

// 具体的被观察者
class Publisher implements Topic {
    private final List<Observer> observers = new ArrayList<>();

    @Override
    public void addObserver(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeObserver(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void notifyObservers(String message) {
        for (Observer observer : observers) {
            observer.receive(message);
        }
    }
}

public class ObserverTest {
    public static void main(String[] args) {
        Publisher publisher = new Publisher();
        Observer user1 = new UserEntity("Tom");
        Observer user2 = new UserEntity("Jerry");

        publisher.addObserver(user1);       //Tom 收到通知: 新文章发布了！
        publisher.addObserver(user2);       //Jerry 收到通知: 新文章发布了！
        publisher.notifyObservers("新文章发布了！");
    }
}